package game.towers;

import game.units.Unit;
import game.units.UnitPool;

import java.awt.Color;
import java.awt.Graphics2D;

import utils.DBG;
import utils.GameMaths;

public abstract class Tower extends Unit {

	static int cost = 2;
	int attack;
	int range;
	Unit objective;
	double attack_delay;
	double attack_time;
	boolean waiting = false;

	public Tower(int xpos, int ypos) {
		super(xpos, ypos);
		attack = 1;
		range = 200;
		objective = null;
		attack_delay = 1000;
		attack_time = -1;
	}

	private void attack() {
		if (objective != null) {
			DBG.showMsg("objective Before live : " + objective.getHealth(),
					this);
			objective.substract(attack);
			waiting = true;
			DBG.showMsg("objective After live " + objective.getHealth(), this);
		} else {
			DBG.showMsg("objective null", this);
		}
	}

	private boolean canAttack() {
		boolean can_attack = false;
		if (attack_time == -1) {
			attack_time = System.currentTimeMillis();
		}
		if (System.currentTimeMillis() - attack_time > attack_delay) {
			waiting = false;
			can_attack = true;
			attack_time = System.currentTimeMillis();
		}
		return can_attack;
	}

	private boolean objectiveInRange() {
		boolean can_attack = false;
		if (objective != null) {
			if (GameMaths.distance(this.getX(), this.getY(), objective.getX(),
					objective.getY()) <= (this.range / 2)) {
				can_attack = true;
			} else {
				can_attack = false;
			}
		}
		return can_attack;
	}

	public void doAttack(UnitPool pool) {
		if (objective == null) {
			objective = pool.getClosest(this);
		}
	}

	@Override
	public Unit clone() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int getNavigationType() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void move(float x, float y) {
		// TODO Auto-generated method stub

	}

	@Override
	public void substract(int live_lost) {
		// TODO Auto-generated method stub

	}

	@Override
	public void renderComponent(Graphics2D g2d) {
		// TODO Auto-generated method stub
		g2d.setColor(Color.black);
		g2d.drawOval((int) this.getX() - 15, (int) this.getY() - 15, 30, 30);

		g2d.drawOval((int) this.getX() - (range / 2), (int) this.getY()
				- (range / 2), this.range, this.range);
		if (objective != null) {
			if (objectiveInRange()) {

				if (canAttack() && objectiveInRange()) {
					g2d.setColor(Color.red);
				} else {
					g2d.setColor(Color.green);
				}
				g2d.drawLine((int) this.getX(), (int) this.getY(),
						(int) objective.getX(), (int) objective.getY());

				g2d.setColor(Color.black);
			}
		}
	}

	@Override
	public void updateLogic() {
		// TODO Auto-generated method stub
		if (!(objectiveInRange())) {
			objective = null;
		}
		if (objective != null && objective.getHealth() <= 0) {
			objective = null;
		}
		if (!waiting && objectiveInRange()) {
			this.attack();
		}
	}

}
